package com.easyadmin.pro.modules.sys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.easyadmin.pro.modules.sys.vo.RoleRelevance;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.easyadmin.pro.modules.sys.entity.UserRoleEntity;
import com.easyadmin.pro.modules.sys.mapper.UserRoleMapper;
import com.easyadmin.pro.modules.sys.service.IUserRoleService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author xulin
 * @since 2024-04-02
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements IUserRoleService {



    @Override
    public void roleRelevance(RoleRelevance roleRelevance) {
        Long userId = roleRelevance.getUserId();
        List<UserRoleEntity> userRoleInfos = new ArrayList<>();
        List<Long> roleIds = roleRelevance.getRoleIds();
        this.remove(new QueryWrapper().eq(UserRoleEntity::getUserId, userId)
                .notIn(UserRoleEntity::getRoleId, roleIds));
        List<Long> oldRoleIds = this.listAs(new QueryWrapper().select(UserRoleEntity::getRoleId)
                .eq(UserRoleEntity::getUserId, userId), Long.class);
        if (CollectionUtil.isNotEmpty(roleIds)) {
            roleIds.forEach(roleId -> {
                if (!oldRoleIds.contains(roleId)) {
                    UserRoleEntity userRoleEntity = new UserRoleEntity();
                    userRoleEntity.setUserId(userId)
                            .setRoleId(roleId);
                    userRoleInfos.add(userRoleEntity);
                }
            });
            if (CollectionUtil.isNotEmpty(userRoleInfos)) {
                this.saveOrUpdateBatch(userRoleInfos);
            }
        }
    }

    @Override
    public List<String> associatedRoleInfo(Long userId) {
        List<String> roleIds = this.listAs(new QueryWrapper()
                .select(UserRoleEntity::getRoleId)
                .eq(UserRoleEntity::getUserId, userId), String.class);
        return roleIds;
    }
}
